#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.
#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import application, cis, command, compatibleunit, geography, staker, symbology, unsorted
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
import os, csv, shutil, datetime, time, reportlab, djangoproject.settings
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib import admin
import _mysql as mysql

class OMSCustomer(models.Model):
    """OMSCustomer is a table of Customer data pulled from the OMS that is pulled from the CIS"""
    AccountNumber=models.TextField(null=True, blank=True)
    MeterNumber=models.TextField(null=True, blank=True)
    LastName=models.TextField(null=True, blank=True)
    FirstName=models.TextField(null=True, blank=True)
    Address1=models.TextField(null=True, blank=True)
    Address2=models.TextField(null=True, blank=True)
    City=models.TextField(null=True, blank=True)
    State=models.TextField(null=True, blank=True)
    ZipCode=models.TextField(null=True, blank=True)
    PhoneNumber=models.TextField(null=True, blank=True)
    AlternatePhoneNumber=models.TextField(null=True, blank=True)
    MapLocation=models.TextField(null=True, blank=True)
    ServiceLocation=models.TextField(null=True, blank=True)
    AMRNumber=models.TextField(null=True, blank=True)
    CalculatedOldMapNumber=models.CharField(max_length=250, blank=True)
    CalculatedDCSINumber=models.CharField(max_length=250, blank=True)
    class Meta:
        db_table=u'coopgisomscustomer'
        app_label='djangoproject'
    def RebuildAllRecords(self):
        OMSDatabase=mysql.connect(host=djangoproject.settings.COOPGISOMSConnectionHost,
                                  user=djangoproject.settings.COOPGISOMSConnectionUserName,
                                  passwd=djangoproject.settings.COOPGISOMSConnectionPassword,
                                  db=djangoproject.settings.COOPGISOMSConnectionDatabase)
        OMSDatabase.query("""SELECT customer.AccountNumber, customer.MeterNumber, customer.LastName, customer.FirstName,
                                   customer.Address1, customer.Address2, customer.City, customer.State, customer.ZipCode, customer.Phone,
                                   customer.AltPhone, customer.MapLocation, customer.ServiceLocation, mtr.AMRnbr from customer
                                   LEFT JOIN mtr ON customer.MeterNumber = mtr.Meter""")
        QuerySet=OMSDatabase.store_result()
        Next=QuerySet.fetch_row()[0]
        OMSCustomer.objects.all().delete()
        while(Next):
            New=OMSCustomer()
            New.AccountNumber=str(Next[0])
            New.MeterNumber=str(Next[1])
            New.LastName=str(Next[2])
            New.FirstName=str(Next[3])
            New.Address1=str(Next[4])
            New.Address2=str(Next[5])
            New.City=str(Next[6])
            New.State=str(Next[7])
            New.ZipCode=str(Next[8])
            New.Phone=str(Next[9])
            New.AltPhone=str(Next[10])
            New.MapLocation=str(Next[11])
            New.ServiceLocation=str(Next[12])
            New.AMRNumber=str(Next[13])
            try:
                New.SetCalculatedOldMapNumber()
            except ValueError:
                print 'MapLocation' + New.MapLocation + '   MeterNumber:  ' + str(New.MeterNumber) + '  Account#:' + str(New.AccountNumber) + '  Name:  ' + str(New.FirstName) + ' ' + str(New.LastName)
                New.CalculatedOldMapNumber=''
            New.SetCalculatedDCSINumber()
            New.save()
            try:
                Next=QuerySet.fetch_row()[0]
            except:
                Next=None
    def SetCalculatedOldMapNumber(self):
        Length=len(self.MapLocation)
        if(Length < 10 or Length > 11):
           raise(ValueError)
        if(Length == 10):
            FirstNumber=int(self.MapLocation[0])
            SecondNumber=int(self.MapLocation[1:4])
            ThirdNumber=int(self.MapLocation[4:7])
            FourthNumber=int(self.MapLocation[8:])
            if(ThirdNumber > 99):
                ThirdNumber = str(int(str(ThirdNumber)[0])) + '-' + str(int(str(ThirdNumber)[1:]))
            self.CalculatedOldMapNumber = str(FirstNumber) + '-' + str(SecondNumber) + '-' + str(ThirdNumber) + '-' + str(FourthNumber)
        elif(Length == 11):
            if(int(self.MapLocation[:3]) == 500):
                ENumberIndicator=True
            else:
                ENumberIndicator=False
            if(ENumberIndicator):
                FirstNumber=int(self.MapLocation[3:6])
                SecondNumber=int(self.MapLocation[6:8])
                ThirdNumber=int(self.MapLocation[8:])
                if(SecondNumber):
                    self.CalculatedOldMapNumber = 'E' + str(FirstNumber) + '-' + str(SecondNumber) + '-' + str(ThirdNumber)
                else:
                    self.CalculatedOldMapNumber = 'E' + str(FirstNumber) + '-' + str(ThirdNumber)
            else:
                FirstNumber=int(self.MapLocation[0:2])
                SecondNumber=int(self.MapLocation[2:5])
                ThirdNumber=int(self.MapLocation[5:8])
                FourthNumber=int(self.MapLocation[8:])
                if(ThirdNumber > 99):
                    ThirdNumber = str(int(str(ThirdNumber)[0])) + '-' + str(int(str(ThirdNumber)[1:]))
                self.CalculatedOldMapNumber = str(FirstNumber) + '-' + str(SecondNumber) + '-' + str(ThirdNumber) + '-' + str(FourthNumber)
    def SetCalculatedDCSINumber(self):
        self.CalculatedDCSINumber=str(int(str(self.MeterNumber).strip()))
    def ConsoleDisplayMatchingMeters(self):
        OMSCustomers=OMSCustomer.objects.all().order_by('id')
        for oMSCustomer in OMSCustomers:
            if(oMSCustomer.AMRNumber):
                FoundNonZero=False
                StrippedMeterDCSINumber=[]
                for character in oMSCustomer.AMRNumber:
                    if(character == '0' and not FoundNonZero):
                        pass
                    else:
                        StrippedMeterDCSINumber.append(character)
                        FoundNonZero=True
                StrippedMeterDCSINumber=''.join(StrippedMeterDCSINumber)
                if(len(Assembly.objects.filter(MeterDCSINumber=StrippedMeterDCSINumber))):
                    Meter=Assembly.objects.filter(MeterDCSINumber=StrippedMeterDCSINumber)[0]
                    print "Found " + str(len(Assembly.objects.filter(MeterDCSINumber=StrippedMeterDCSINumber))) + ":  " + \
                                                  oMSCustomer.MeterNumber + ', ' +  oMSCustomer.AMRNumber + '         ' +\
                                                  str(Meter.MeterNumber)  +', ' + str(Meter.MeterDCSINumber)
                    MeterDCSINumberMatchesFound=MeterDCSINumberMatchesFound + 1
                    #Would update the GIS record for the Meter Assembly here...
                else:
                    print "No Match found for MeterDCSI Number:  " + str(Results[i].AMRNumber)
                    MeterDCSINumberMatchesNotFound = MeterDCSINumberMatchesNotFound + 1





class OMSSubstationMap(models.Model):
    """OMSSubstationMap maps OMS Substation Numbers with COOPGIS Substation Numbers"""
    GISSubstationNumber=models.TextField(null=True, blank=True, unique=True)
    OMSSubstationNumber=models.TextField(null=True, blank=True)
    class Meta:
        db_table=u'coopgisomssubstationmap'
        app_label='djangoproject'

class OMSCircuitMap(models.Model):
    """OMSCircuitMap maps OMS Circuit Numbers with COOPGIS Circuit Numbers"""
    GISCircuitNumber=models.TextField(null=True, blank=True, unique=True)
    OMSCircuitNumber=models.TextField(null=True, blank=True)
    class Meta:
        db_table=u'coopgisomscircuitmap'
        app_label='djangoproject'






